﻿using NLog;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using WTAppletProjectHTTPS.Models;

namespace WTAppletProjectHTTPS.Controllers
{
    
    public class ProductAssociationDateQueryController : ApiController
    {
        private static readonly Logger Logger = NLog.LogManager.GetCurrentClassLogger();
        // POST api/<controller>
        public async Task<HttpResponseMessage> Post([FromBody] ProductAssociationDateQuery PADQ)
        {
            ReturnObjectQuery RO = new ReturnObjectQuery();
            if (PADQ == null || PADQ.PageNumber <= 0 || PADQ.PageSize <= 0)
            {
                Logger.Warn("参数无效");
                RO.Status = HttpStatusCode.BadRequest;
                RO.Message = "参数无效";
                RO.Data = null;
                Logger.Error("参数无效");
                return Request.CreateResponse(HttpStatusCode.BadRequest, RO);
            }

            try
            {
                using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionName"].ConnectionString))
                {
                    await connection.OpenAsync();

                    var whereClause = "WHERE 1=1";
                    if (PADQ.PAD_ID != 0)
                    {
                        whereClause += " AND PADID = @ID";
                    }
                    if (PADQ.PAD_Date.HasValue)
                    {
                        whereClause += " AND PADDate = @Date";
                    }
                    if (!string.IsNullOrEmpty(PADQ.PAD_LineBody))
                    {
                        whereClause += " AND PADLineBody LIKE @LineBody";
                    }
                    if (!string.IsNullOrEmpty(PADQ.PAD_ProductInformation))
                    {
                        whereClause += " AND PADProductInformation LIKE @ProductInformation";
                    }
                    if (!string.IsNullOrEmpty(PADQ.PAD_ModuleProductionDatePhotoScan))
                    {
                        whereClause += " AND PADModuleProductionDatePhotoScan LIKE @ModuleProductionDatePhotoScan";
                    }

                    var query = $@"
                        SELECT 
                            PADID, PADDate, PADLineBody, PADProductInformation, PADModuleProductionDatePhotoScan,PADCreateCreator,PADCreateTime,
                            COUNT(*) OVER() AS TotalCount
                        FROM 
                            (SELECT 
                                PADID, PADDate, PADLineBody, PADProductInformation, PADModuleProductionDatePhotoScan,PADCreateCreator,PADCreateTime,
                                ROW_NUMBER() OVER(ORDER BY PADID) AS RowNum
                             FROM ProductAssociationDate {whereClause}) AS Result
                        WHERE 
                            RowNum BETWEEN @StartRow AND @EndRow
                        ORDER BY RowNum";

                    int startRow = (PADQ.PageNumber - 1) * PADQ.PageSize + 1;
                    int endRow = PADQ.PageNumber * PADQ.PageSize;

                    var parameters = new List<SqlParameter>
                    {
                        new SqlParameter("@StartRow", SqlDbType.Int) { Value = startRow },
                        new SqlParameter("@EndRow", SqlDbType.Int) { Value = endRow }
                    };

                    if (PADQ.PAD_ID != 0)
                    {
                        parameters.Add(new SqlParameter("@ID", SqlDbType.Int) { Value = PADQ.PAD_ID });
                    }

                    if (PADQ.PAD_Date.HasValue)
                    {
                        parameters.Add(new SqlParameter("@Date", SqlDbType.DateTime) { Value = PADQ.PAD_Date.Value });
                    }

                    if (!string.IsNullOrEmpty(PADQ.PAD_LineBody))
                    {
                        parameters.Add(new SqlParameter("@LineBody", SqlDbType.NVarChar, 50) { Value = $"%{PADQ.PAD_LineBody}%" });
                    }

                    if (!string.IsNullOrEmpty(PADQ.PAD_ProductInformation))
                    {
                        parameters.Add(new SqlParameter("@ProductInformation", SqlDbType.NVarChar, 100) { Value = $"%{PADQ.PAD_ProductInformation}%" });
                    }

                    if (!string.IsNullOrEmpty(PADQ.PAD_ModuleProductionDatePhotoScan))
                    {
                        parameters.Add(new SqlParameter("@ModuleProductionDatePhotoScan", SqlDbType.NVarChar, 100) { Value = $"%{PADQ.PAD_ModuleProductionDatePhotoScan}%" });
                    }

                    using (var command = new SqlCommand(query, connection))
                    {
                        command.Parameters.AddRange(parameters.ToArray());
                        using (var reader = await command.ExecuteReaderAsync())
                        {
                            if (!reader.HasRows)
                            {
                                Logger.Warn("未找到记录");
                                RO.Status = HttpStatusCode.NotFound;
                                RO.Message = "未找到记录";
                                RO.Data = null;
                                return Request.CreateResponse(HttpStatusCode.NotFound, RO);
                            }

                            var products = new List<ProductAssociationDate>();
                            int totalCount = 0;
                            while (await reader.ReadAsync())
                            {
                                if (totalCount == 0)
                                {
                                    totalCount = reader.GetInt32(reader.GetOrdinal("TotalCount"));
                                }

                                products.Add(new ProductAssociationDate
                                {
                                    PAD_ID = reader.GetInt32(reader.GetOrdinal("PADID")),
                                    PAD_Date = reader.GetDateTime(reader.GetOrdinal("PADDate")),
                                    PAD_LineBody = reader.GetString(reader.GetOrdinal("PADLineBody")),
                                    PAD_ProductInformation = reader.GetString(reader.GetOrdinal("PADProductInformation")),
                                    PAD_ModuleProductionDatePhotoScan = reader.GetString(reader.GetOrdinal("PADModuleProductionDatePhotoScan")),
                                    PAD_CreateCreator = reader.GetString(reader.GetOrdinal("PADCreateCreator")),
                                    PAD_CreateTime = reader.GetDateTime(reader.GetOrdinal("PADCreateTime"))
                                });
                            }

                            Logger.Warn("未找到记录");
                            RO.Status = HttpStatusCode.OK;
                            RO.Message = "OK";
                            RO.Data = products;
                            RO.TotalCount = totalCount;
                            RO.PageNumber = PADQ.PageNumber;
                            RO.PageSize = PADQ.PageSize;
                            return Request.CreateResponse(HttpStatusCode.OK, RO);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Error("查询失败: " + ex.Message);
                RO.Status = HttpStatusCode.InternalServerError;
                RO.Message = "Error: " + ex.Message;
                RO.Data = null;
                return Request.CreateResponse(HttpStatusCode.InternalServerError, RO);
            }
        }
    }
}